package cn.chencq.spider.novel.service.chapter.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.chencq.spider.novel.service.AbstractSpider;
import cn.chencq.spider.novel.service.chapter.IChapterSpider;
import cn.chencq.spider.novel.utils.SpiderRuleUtils;
import cn.chencq.spider.novel.utils.Utils;
import cn.chencq.spider.novel.vo.Book;
import cn.chencq.spider.novel.vo.Chapter;
import cn.chencq.spider.novel.vo.Selector;

public class ChapterSpider extends AbstractSpider implements IChapterSpider {
	
	@Override
	public List<Chapter> getsChapter(Book book) {
		AtomicInteger count = new AtomicInteger(0);
		List<Chapter> chapterList = new ArrayList<Chapter>();
		String url = book.getUrl() + "#Catalog";
		try {
			Document doc = super.crawl(url);
			String domain = Utils.getDomain(url);// 获取链接的主站域名
			Selector selector = SpiderRuleUtils.getSpiderSelector(domain);
			Elements trs = doc.select(selector.getChapterListSelector());
			for (Element tr : trs) {
				String chapterName = tr.html();
				String chapterUrl = tr.absUrl("href");
				chapterList.add(new Chapter(book.getBookId(), chapterName, chapterUrl, count.incrementAndGet()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return chapterList;
	}

}
